<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.roleName" class="list-input" placeholder="搜索角色名称、权限字符"
               @input="handleSearchInput" @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.roleName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">权限字符</text>
            <uni-easyinput v-model="queryParams.roleKey" placeholder="请输入权限字符" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="全部状态" title="选择状态"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">创建时间</text>
            <uni-datetime-picker v-model="queryParams.createTime" type="daterange" placeholder="选择时间范围"
                                 :clearIcon="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">数据权限</text>
            <BottomSelect v-model="queryParams.dataScope" :options="dataScopeOptions" value-field="value"
                          label-field="text" placeholder="全部权限" title="选择数据权限"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:role:add'])">
        <uni-icons type="plus" size="14" color="#007aff"></uni-icons>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"></uni-icons>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="role in roleList" :key="role.roleId" class="list-item" @click="handleView(role)">
        <view class="list-avatar">
          <uni-icons :type="getRoleIcon(role)" size="24" :color="getRoleIconColor(role)"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ role.roleName }}</text>
            <text class="list-subtitle">{{ role.roleKey }}</text>
            <view class="status-badge" :class="role.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ role.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">{{ getDataScopeText(role.dataScope) }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="up-down" size="14" color="#999"/>
              <text class="detail-text">第{{ role.roleSort }}位</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(role.createTime, '{y}-{m}-{d}') }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions" v-if="role.roleId !== 1">
          <view class="action-btn action-primary" @click.stop="handleEdit(role)"
                v-if="checkPermission(['system:role:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-default" @click.stop="handleAuth(role)"
                v-if="checkPermission(['system:role:edit'])">
            <uni-icons type="settings" size="14" color="#666"/>
            <text class="action-text">权限</text>
          </view>
          <view class="action-btn" :class="role.status === '0' ? 'action-warning' : 'action-success'"
                @click.stop="handleChangeStatus(role)" v-if="checkPermission(['system:role:edit'])">
            <uni-icons :type="role.status === '0' ? 'close' : 'checkmarkempty'" size="14"
                       :color="role.status === '0' ? '#ff9500' : '#34c759'"/>
            <text class="action-text">{{ role.status === '0' ? '停用' : '启用' }}</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(role)"
                v-if="checkPermission(['system:role:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="roleList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && roleList.length === 0" class="list-empty">
      <uni-icons type="staff" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无角色数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:role:add'])">添加角色</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {changeRoleStatus, delRole, listRole} from '@/api/system/role'
import {parseTime} from '@/utils/ruoyi'

import {usePermission} from '@/utils/permission'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()


const checkPermission = usePermission()

// 数据定义
const roleList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: '',
  roleKey: '',
  status: '',
  dataScope: '',
  createTime: ''
})

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

// 数据权限选项
const dataScopeOptions = [
  {value: '', text: '全部权限'},
  {value: '1', text: '全部数据权限'},
  {value: '2', text: '自定数据权限'},
  {value: '3', text: '本部门数据权限'},
  {value: '4', text: '本部门及以下数据权限'},
  {value: '5', text: '仅本人数据权限'}
]

const filterPopup = ref(null)

// 页面加载
onMounted(() => {
  getList()
})

// 获取角色列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listRole(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        roleList.value = newData
      } else {
        roleList.value.push(...newData)
      }

      total.value = response.total || 0

      if (roleList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    proxy.$modal.showToast('获取角色列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 过滤抽屉事件
let searchTimer = null

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    roleName: '',
    roleKey: '',
    status: '',
    dataScope: '',
    createTime: ''
  })
}

// 获取角色图标
function getRoleIcon(role) {
  if (role.roleId === 1) return 'star-filled'
  if (role.admin) return 'staff-filled'
  return 'person-filled'
}

// 获取角色图标颜色
function getRoleIconColor(role) {
  if (role.roleId === 1) return '#ff4d4f'
  if (role.admin) return '#faad14'
  return '#1890ff'
}

// 获取数据权限文本
function getDataScopeText(dataScope) {
  const scopeMap = {
    '1': '全部数据权限',
    '2': '自定数据权限',
    '3': '本部门数据权限',
    '4': '本部门及以下数据权限',
    '5': '仅本人数据权限'
  }
  return scopeMap[dataScope] || '未知权限'
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.roleName = '';
  handleQuery()
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  roleList.value = []
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: './edit?mode=add'
  })
}

function handleEdit(role) {
  uni.navigateTo({
    url: `./edit?mode=edit&roleId=${role.roleId}`
  })
}

function handleView(role) {
  uni.navigateTo({
    url: `./edit?mode=view&roleId=${role.roleId}`
  })
}

function handleAuth(role) {
  uni.navigateTo({
    url: `./authUser?roleId=${role.roleId}`
  })
}

async function handleChangeStatus(role) {
  try {
    const newStatus = role.status === '0' ? '1' : '0'
    const statusText = newStatus === '0' ? '启用' : '停用'

    await proxy.$modal.confirm(`确认要${statusText}角色"${role.roleName}"吗？`)

    const response = await changeRoleStatus(role.roleId, newStatus)
    if (response.code === 200) {
      role.status = newStatus
      proxy.$modal.showToast(`${statusText}成功`)
    }
  } catch (error) {
    console.error('修改状态失败:', error)
  }
}

async function handleDelete(role) {
  try {
    await proxy.$modal.confirm(`确认要删除角色"${role.roleName}"吗？`)

    const response = await delRole(role.roleId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除角色失败:', error)
  }
}


function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>
